package org.example.server8001.controller;

import org.example.SystemDemo.comment.res.HostinfoListRES;
import org.example.SystemDemo.core.Result;
import org.example.SystemDemo.comment.enity.*;
import org.example.SystemDemo.utils.JSONUtil;
import org.example.server8001.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * 主机列表
 */
@RestController
@RequestMapping("/v1/hostlist")
public class HostListController {

    @Autowired
    private ForwardController forwardController;

    @Autowired
    private InfoService infoService;

    /**
     * 获取主机列表
     * @return 返回列表
     */
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public Result<ArrayList<HostinfoListRES>> getHostInfoList(){
        ArrayList<HostinfoListRES> hostRES = new ArrayList<>();
        final List<HostInfo> list = infoService.list();
        for( HostInfo info : list){
            if (!info.isConnectStatus()){
                hostRES.add(new HostinfoListRES(info));
                continue;
            }

            final ClientInfo client = new ClientInfo(info.getId(),info.getHostIp(), info.getRunPort());

            // 获取cpu使用率
            final CPU cpu = forwardController.getDyCpuInfo(client).getData();

            // 获取内存使用率
            final Memory memory = forwardController.getDyMemoryInfo(client).getData();

            // 获取网络带宽 这里不知道为什么ArrayList改成了 LinkedHashMap
            final List<Net> nets = JSONUtil.parseArray(JSONUtil.stringify(forwardController.getDyNetInfo(client).getData()),Net.class);

            // 获取磁盘使用率
            final List<Disk> disks = JSONUtil.parseArray(JSONUtil.stringify(forwardController.getDyDiskInfo(client).getData()),Disk.class);

            hostRES.add(new HostinfoListRES(info,cpu,memory,nets,disks));

        }
        return Result.ok(hostRES);
    }
}
